package com.patchmanage.back.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.patchmanage.back.annotation.LoginValidate;
import com.patchmanage.back.config.Constants;
import com.patchmanage.back.exception.SystemException;
import com.patchmanage.back.redis.JedisTemplate;
import com.patchmanage.back.result.CodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;



import cn.hutool.core.util.StrUtil;

/**
 * @describe： 登录验证拦截器 @author：HuiZhao  
 * @createTime：2019年3月25日 下午2:33:06    
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

	@Autowired
	private JedisTemplate<String> jedisTemplate;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		// 判断接口是否需要登录
		LoginValidate methodAnnotation = method.getAnnotation(LoginValidate.class);
		// 有 @LoginValidate 注解，需要认证
		if (methodAnnotation != null) {
			// 执行认证057978c5f92a4180b5e017d9ce36a4cb
			String token = request.getHeader("token");
	    	
			if (StrUtil.isBlank(token)) {
				throw new SystemException(CodeMsg.TOKEN_EMPTY);
			}
			String tokenFromRedis = jedisTemplate.get(Constants.userToken + token);
			if (StrUtil.isBlank(tokenFromRedis)) {
				throw new SystemException(CodeMsg.TOKEN_EMPTY);
			}
			jedisTemplate.expire(Constants.userToken + token, 1800);
		}
		return true;
	}
}